<template>
    <div class="form-page">
        <el-form
            ref="form"
            :model="form"
            :inline="true"
            :rules="formRule"
            label-width="10em"
            class="data-from"
        >
            <div class="form-item xy-start al-str">
                <div class="title">基础信息</div>
                <div class="yx-start al-start data">
                    <el-form-item
                        v-if="isAdd"
                        prop="classificationId"
                        label="学科"
                    >
                        <el-cascader
                            ref="classification"
                            :key="zeroOne"
                            v-model="form.classificationId"
                            :props="classificationProps"
                            :show-all-levels="false"
                            filterable
                            clearable
                            @change="changeClassification"
                        ></el-cascader>
                    </el-form-item>
                    <el-form-item label="栏目名称" prop="name">
                        <el-input v-model="form.name"></el-input>
                    </el-form-item>
                    <el-form-item label="排序" prop="sort">
                        <el-input
                            v-model="form.sort"
                            type="number"
                            min="1"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="是否免费" prop="sort">
                        <el-radio-group v-model="form.isFree">
                            <el-radio :label="false">收费</el-radio>
                            <el-radio :label="true">免费</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </div>
            </div>
            <div class="form-item xy-start al-str">
                <div class="title">模式设置</div>
                <div class="yx-start al-start data">
                    <div>
                        <div v-for="(item, index) in form.model" :key="index">
                            <el-form-item
                                :label="columnModel[item.type]"
                                :prop="columnModel[item.type]"
                            >
                                <el-radio v-model="isDefault" :label="item.type"
                                    >是否默认</el-radio
                                >
                            </el-form-item>
                            <el-button
                                type="danger"
                                icon="el-icon-delete"
                                circle
                                @click.native="deleteModel(index)"
                            ></el-button>
                        </div>
                        <div style="margin-left: 26%">
                            <el-button round @click.native="addModel"
                                >添加选项</el-button
                            >
                        </div>
                    </div>
                </div>
            </div>
            <div class="form-item xy-start al-str">
                <div class="title">内容设置</div>
                <div class="yx-start al-start data">
                    <el-form-item label="类型" prop="type">
                        <el-radio-group
                            v-model="form.type"
                            @change="choicePaperOrChapters"
                        >
                            <el-radio label="paperColumn" border>试卷</el-radio>
                            <el-radio label="chapterColumn" border
                                >章节</el-radio
                            >
                        </el-radio-group>
                    </el-form-item>
                    <div>
                        <div v-if="isPaper">
                            <div
                                v-for="(item, index) in paperContent"
                                :key="index"
                            >
                                <el-form-item label="试卷" prop="paper">
                                    <el-input v-model="item.name" > </el-input>
                                </el-form-item>
                                <el-form-item label="是否免费">
                                    <el-radio-group v-model="item.isFree">
                                        <el-radio :label="0">收费</el-radio>
                                        <el-radio :label="1">免费</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                                <el-button
                                    type="danger"
                                    icon="el-icon-delete"
                                    circle
                                    @click.native="deletePaper(index)"
                                ></el-button>
                            </div>
                            <div style="margin-left: 26%">
                                <el-button round @click.native="addPaper"
                                    >添加试卷</el-button
                                >
                            </div>
                        </div>
                        <div v-else>
                            <div>
                                <el-form-item label="父章节">
                                    <el-cascader
                                        ref="chapter"
                                        v-model="parentChapter"
                                        :props="chapterProps"
                                        :show-all-levels="false"
                                        filterable
                                        clearable
                                        @change="addChapterContent"
                                    >
                                    </el-cascader>
                                </el-form-item>
                            </div>
                            <div
                                v-for="(item, index) in chapterContent"
                                :key="index"
                            >
                                <el-form-item label="章节" prop="chapter">
                                    <el-input v-model="item.name"> </el-input>
                                </el-form-item>
                                <el-form-item label="是否免费">
                                    <el-radio-group v-model="item.isFree">
                                        <el-radio :label="0">收费</el-radio>
                                        <el-radio :label="1">免费</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                                <el-button
                                    type="danger"
                                    icon="el-icon-delete"
                                    circle
                                    @click.native="deleteChapter(index)"
                                ></el-button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </el-form>
        <div ref="submitDiv" class="form-item xy-center from-operation">
            <el-button
                type="primary"
                icon="el-icon-folder"
                :loading="submitFlag"
                @click="save"
                >保存
            </el-button>
            <el-button
                type="warning"
                icon="el-icon-delete-solid"
                :loading="submitFlag"
                @click="clickCancel('column-list')"
                >取消
            </el-button>
        </div>
        <el-dialog
            v-if="dialogAddPaperVisible"
            title="添加试卷"
            :visible.sync="dialogAddPaperVisible"
        >
            <el-form
                ref="paperForm"
                :model="paperForm"
                label-width="10em"
                class="table-edit-from"
            >
                <el-form-item label="试卷类型" prop="paperType">
                    <el-select
                        v-model="paperForm.paperType"
                        clearable
                        placeholder="请选择"
                        @clear="cleanPaper"
                        @change="selectPaper(paperForm.paperType)"
                    >
                        <el-option
                            v-for="item in paperTypeOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="试卷" prop="paperId">
                    <el-select
                        v-model="paperForm.paperId"
                        clearable
                        multiple
                        filterable
                        placeholder="请选择"
                    >
                        <el-option
                            v-for="item in paperOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogAddPaperVisible = false"
                    >取 消</el-button
                >
                <el-button type="primary" @click="addPaperContent"
                    >确 定</el-button
                >
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { FormPage } from "@/layout/mixin/iVue.js";
import { mapState } from "vuex";
import {
    fetchCategoryChildren,
    fetchCategoryFirstStage,
    fetchClassificationChildren,
    fetchClassificationFirst
} from "@/api/course";
import {
    fetchChapterChildren,
    fetchChapterFirstStage,
    fetchPaper
} from "@/api/exam";
import { get, put, post } from "@/api/request";
import paperComponent from "@/views/models/exam/component/paperComponent";

export default {
    name: "ColumnAdd",
    components: {
        paperComponent
    },
    mixins: [FormPage],
    data() {
        return {
            isAdd: false,
            dialogAddPaperVisible: false,
            category: null,
            zeroOne: 0,
            zeroTwo: 0,
            isDefault: 1,
            isFree: 0,
            isPaper: true,
            isDisabled: false,
            parentChapter: null,
            paperTypeOptions: [
                {
                    value: "chapterText",
                    label: "章节测试"
                },
                {
                    value: "finalExam",
                    label: "期末考试"
                },
                {
                    value: "normalExam",
                    label: "普通考试"
                }
            ],
            paperForm: {
                classificationId: null,
                paperId: null,
                name: null
            },
            paperType: null,
            paperQueryData: {
                paperType: null,
                pageSize: 999,
                currentPage: 1,
                classificationId: null
            },
            paperOptions: [],
            form: {
                id: null,
                name: null,
                classificationId: null,
                sort: null,
                type: "paperColumn",
                isFree: false,
                model: [
                    {
                        type: 1,
                        isDefault: 1
                    },
                    {
                        type: 2,
                        isDefault: 0
                    },
                    {
                        type: 3,
                        isDefault: 0
                    }
                ],
                content: null
            },
            formRule: {
                category: [
                    {
                        required: true,
                        message: "请选择课程类别！",
                        trigger: "change"
                    }
                ],
                classificationId: [
                    {
                        required: true,
                        message: "请选择学科！",
                        trigger: "change"
                    }
                ],
                name: [
                    { required: true, message: "请输入名称！", trigger: "blur" }
                ],
                sort: [
                    {
                        required: true,
                        message: "请输入排序序号",
                        trigger: "blur"
                    }
                ]
            },
            paperContent: [],
            chapterContent: [],
            actions: null,
            actionSearch: null,
            categoryProps: {
                emitPath: false,
                lazy: true,
                checkStrictly: false,
                lazyLoad: this.fetchCategory
            },
            classificationProps: {
                emitPath: false,
                lazy: true,
                checkStrictly: true,
                lazyLoad: this.fetchClassification
            },
            chapterProps: {
                emitPath: false,
                lazy: true,
                checkStrictly: true,
                lazyLoad: this.fetchChapter
            }
        };
    },
    computed: {
        ...mapState({
            columnModel: state => state.status.columnModel
        })
    },
    watch: {
        actionSearch(val) {
            this.$refs.tree.filter(val);
        }
    },
    methods: {
        async loadData(id) {
            this.isAdd = id === undefined;
            return Promise.all([this.loadUserOld(id)]).catch(e => {
                console.error(e);
                this.$message.error("数据加载失败，请稍后在试");
            });
        },
        async loadUserOld(id) {
            if (!id) return;
            get(`/exam/column/detail/${id}`).then(result => {
                let typeVal = result.courseCategoryId;
                this.category = typeVal;
                this.form.classificationId = [];
                ++this.zeroOne;
                result.classificationId = result.classificationIds;
                result.category = [typeVal];
                this.category = result.category;
                this.form = result;
                if (result.type === "paperColumn") {
                    this.isPaper = true;
                    this.paperContent = result.content;
                } else {
                    this.isPaper = false;
                    this.chapterContent = result.content;
                }
                const model = this.form.model;
                for (let i = 0; i < model.length; i++) {
                    if (model[i].isDefault === 1) {
                        this.isDefault = model[i].type;
                    }
                }
                this.isDisabled = true;
            });
        },
        save() {
            // this.dataForm.classificationId = this.$refs.classification.getCheckedNodes()[0].value
            const m = this.form.model;
            const d = this.isDefault;
            for (let i = 0; i < m.length; i++) {
                if (d > m.length) {
                    if (m[i].type === d) {
                        m[i].isDefault = 1;
                    } else {
                        m[i].isDefault = 0;
                    }
                } else {
                    m[0].isDefault = 1;
                }
            }
            if (this.isPaper) {
                this.form.content = this.paperContent;
            } else {
                this.form.content = this.chapterContent;
            }
            if (this.addAction) {
                this.clickSave(
                    "/exam/column/update",
                    this.form,
                    false,
                    "column-list"
                );
            } else {
                this.form.classificationId = this.$refs.classification.getCheckedNodes()[0].value;
                this.clickSave(
                    "/exam/column/update",
                    this.form,
                    true,
                    "column-list"
                );
            }
        },
        choicePaperOrChapters(data) {
            if (data === "paperColumn") {
                this.isPaper = true;
            } else if (data === "chapterColumn") {
                this.isPaper = false;
            }
        },
        addModel() {
            const m = this.form.model;
            if (m.length < 3) {
                this.form.model = [
                    {
                        type: 1,
                        isDefault: 1
                    },
                    {
                        type: 2,
                        isDefault: 0
                    },
                    {
                        type: 3,
                        isDefault: 0
                    }
                ];
            }
        },
        addPaper() {
            if (this.form.classificationId === null) {
                this.$alert("请先选择学科！", "错误", {
                    confirmButtonText: "确定"
                });
            } else {
                this.dialogAddPaperVisible = true;
            }
        },
        addPaperContent() {
            this.dialogAddPaperVisible = false;
            let obj = {};
            const paperIds = this.paperForm.paperId;
            for (let i = 0; i < paperIds.length; i++) {
                obj = this.paperOptions.find(item => {
                    return item.value === paperIds[i];
                });
                const name = obj.label;
                const a = this.paperContent.find(
                    item => item.id === paperIds[i]
                );
                if (!a) {
                    this.paperContent.push({
                        id: paperIds[i],
                        name: name,
                        isFree: 0
                    });
                }
            }
        },
        deleteModel(data) {
            if (this.form.model.length > 1) {
                this.form.model.splice(data, 1);
            }
        },
        deleteChapter(data) {
            this.chapterContent.splice(data, 1);
        },
        deletePaper(data) {
            this.paperContent.splice(data, 1);
        },
        selectPaper(data) {
            this.cleanPaper();
            this.paperOptions = [];
            if (data !== null && data !== "") {
                this.paperQueryData.paperType = data;
                this.paperQueryData.classificationId = this.$refs.classification.getCheckedNodes()[0].value;
                fetchPaper(this.paperQueryData).then(res => {
                    for (let i = 0; i < res.records.length; i++) {
                        this.paperOptions.push({
                            value: res.records[i].id,
                            label: res.records[i].name
                        });
                    }
                });
            }
        },
        cleanPaper() {
            delete this.paperForm.paperId;
        },
        addChapterContent() {
            const pid = this.parentChapter;
            fetchChapterChildren({ id: pid }).then(res => {
                for (let i = 0; i < res.length; i++) {
                    const a = this.chapterContent.find(
                        item => item.id === res[i].id
                    );
                    if (!a) {
                        this.chapterContent.push({
                            id: res[i].id,
                            name: res[i].name,
                            isFree: 0
                        });
                    }
                }
            });
        },
        changeClassification(data) {
            // this.dataForm.classificationId = this.$refs.classification.getCheckedNodes()[0].value
            this.chapterContent = [];
            this.parentChapter = null;
            ++this.zeroTwo;
        },
        changeCategory(data) {
            // this.category = this.$refs.category.getCheckedNodes()[0].value
            this.form.classificationId = [];
            this.chapterContent = [];
            this.parentChapter = null;
            ++this.zeroOne;
        },
        fetchCategory(node, resolve) {
            const { level } = node;
            if (!node.data) {
                fetchCategoryFirstStage().then(res => {
                    const nodes = Array.from(res).map(item => {
                        return {
                            value: item.id,
                            label: `${item.name}`,
                            leaf: level >= (item.children.length > 0 ? 1 : 0)
                        };
                    });
                    resolve(nodes);
                });
            } else {
                fetchCategoryChildren({ id: node.data.value }).then(res => {
                    const nodes = Array.from(res).map(item => {
                        return {
                            value: item.id,
                            label: `${item.name}`,
                            leaf:
                                level >=
                                (item.children.length > 0 ? level + 1 : 0)
                        };
                    });
                    resolve(nodes);
                });
            }
        },
        fetchClassification(node, resolve) {
            const { level } = node;
            if (!node.data) {
                fetchClassificationFirst().then(res => {
                    const nodes = Array.from(res).map(item => {
                        return {
                            value: item.id,
                            label: `${item.name}`,
                            leaf: level >= (item.children.length > 0 ? 1 : 0)
                        };
                    });
                    resolve(nodes);
                });
            } else {
                fetchClassificationChildren({ id: node.data.value }).then(
                    res => {
                        const nodes = Array.from(res).map(item => {
                            return {
                                value: item.id,
                                label: `${item.name}`,
                                leaf:
                                    level >=
                                    (item.children.length > 0 ? level + 1 : 0)
                            };
                        });
                        resolve(nodes);
                    }
                );
            }
        },
        fetchChapter(node, resolve) {
            const { level } = node;
            if (this.form.classificationId !== null) {
                if (!node.data) {
                    let classificationId = this.form.classificationId;
                    if (this.isDisabled) {
                        classificationId = this.form.classificationId[0];
                    }
                    fetchChapterFirstStage({
                        classificationId: classificationId
                    }).then(res => {
                        const nodes = Array.from(res).map(item => {
                            return {
                                value: item.id,
                                label: `${item.name}`,
                                leaf:
                                    level >= (item.children.length > 0 ? 1 : 0)
                            };
                        });
                        resolve(nodes);
                    });
                } else {
                    fetchChapterChildren({ id: node.data.value }).then(res => {
                        const nodes = Array.from(res).map(item => {
                            return {
                                value: item.id,
                                label: `${item.name}`,
                                leaf:
                                    level >=
                                    (item.children.length > 0 ? level + 1 : 0)
                            };
                        });
                        resolve(nodes);
                    });
                }
            }
        }
    }
};
</script>

<style lang="scss" scoped></style>
